#! /usr/bin/python
import socket
import sys
import os
import re
import cPickle
from backupManager.file import file
from time import sleep
import datetime

host = ''
port = 60000
backlog = 5
buffer_size = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
NOTEXIST='notexist'

def indexDrive(commDict):
    if not os.path.exists(commDict['path']):
	return NOTEXIST
    if commDict['validext']:
        validext = '|'.join(commDict['validext'])
        validext = "\.(" + validext + ")$"
    else:
        validext = None
    if commDict['skip']:
    	skip = '|'.join(commDict['skip'])
    else:
	skip = None
    return index('',validext,skip,root=True,commDict=commDict)

def index(path,validext,skipIn,root=False,commDict=None):
    dir = os.path.join(commDict['path'],path)
    #print dir
    if not os.path.isdir(dir):
        print "Can only call index on a directory!\n"
        return None
    try:
        files = os.listdir(dir)
    except:
        return None
    dirObj = file(os.path.basename(dir),
		os.path.dirname(os.path.join(commDict['path'],path)).replace(commDict['path'],'').replace(os.sep,commDict['sep']),
		commDict['name']+":",
		True,
		0,
		0,
		commDict['name'],
		commDict['serial'])
    if skipIn:
    	skip = re.compile(str(skipIn),re.IGNORECASE)
    else:
	skip = None
    passedFiles = []
    if validext:
        #print validext
        ext = re.compile(validext,re.IGNORECASE)
    else:
        ext = None
    for foundFile in files[:]:
        if os.path.islink(os.path.join(dir,foundFile)):
            realFile = os.readlink(os.path.join(dir,foundFile))
        else:
            realFile = os.path.join(dir,foundFile)
        if not os.path.isdir(realFile):
	    if skip:
            	if re.search(skip,foundFile):
               		continue
            if ext:
                if not re.search(ext,foundFile):
                    continue
        newFile = None
        if os.path.isdir(realFile):
            newFile = index(os.path.join(path,foundFile),validext,skip,commDict=commDict)
        else:
            newFile = file(foundFile,
			path.replace(os.sep,commDict['sep']),
			commDict['name']+":",
			False,
			float(os.path.getsize(os.path.join(dir,foundFile)))/float(1024),
			int(os.path.getmtime(os.path.join(dir,foundFile))),
			commDict['name'],
			commDict['serial'])
        if newFile:
            newFile.setParent(dirObj)
            passedFiles.append(newFile)
    if not passedFiles and not root:
        return None
    dirObj.setFiles(passedFiles)
    #print dirObj.getName()
    return dirObj

def write(_socket, data):
    f = _socket.makefile('wb', buffer_size )
    cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL)
    f.close()

def read(_socket):
    f = _socket.makefile('rb', buffer_size )
    data = cPickle.load(f)
    f.close()
    return data

while True:
    client, address = s.accept()
    print "Request from ",address,str(datetime.datetime.now())
    try:
        commDict = read(client)
        if commDict:
	    print commDict
            if type(commDict) == dict:
                rootFile = indexDrive(commDict)
                write(client,rootFile)
    except:
	try:
        	write(client,None)
	except:
		pass
    try:
    	client.close()
    except:
	pass
    print 'Completed',str(datetime.datetime.now())
        
        
